<template>
  <div>
    <h1 style="color: red">Hello World</h1>
    <div class="table">
      <!--给表格添加一个id，导出文件事件需要使用-->
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        id="out-table"
      >
        <el-table-column
          prop="date"
          label="日期"
          width="180"
        >
        </el-table-column>
        <el-table-column
          prop="name"
          label="姓名"
          width="180"
        >
        </el-table-column>
        <el-table-column
          prop="address"
          label="地址"
        >
        </el-table-column>
      </el-table>
      <div style="margin-bottom: 10px"></div>
      <!--给按钮绑定事件-->
      <el-button type="info"  size="mini"  @click="exportExcel">点击导出</el-button>
    </div>


  </div>
</template>

<script>

// 引入导出Excel表格依赖
import FileSaver from "file-saver";
import XLSX from "xlsx";

export default {
  name: "excel",

  data() {
    return {

      tableData: [
        {
          date: "2016-05-02",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1518 弄"
        },
        {
          date: "2016-05-04",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1517 弄"
        },
        {
          date: "2016-05-01",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1519 弄"
        },
        {
          date: "2016-05-03",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1516 弄"
        }
      ]


    }
  },
  methods: {

    // 导出Excel
    exportExcel() {
      if (this.tableData.length <= 0) {
        this.$message({
          type: 'error',
          message: '当前页无可导出的数据！'
        })
        return
      }
      let filename = '个人信息' + Date.now() + '.xlsx'
      let data = [
        [
          '日期',
          '姓名',
          '地址'
        ]
      ]
      this.tableData.map((item) => {
        let arr = []
        arr.push(item.date)
        arr.push(item.name)
        arr.push(item.address)
        data.push(arr)
      })
      let wb = XLSX.utils.book_new() // 工作簿，即一个Excel文件
      let ws = XLSX.utils.aoa_to_sheet(data) // 工作表，即Excel内部的工作表
      XLSX.utils.book_append_sheet(wb, ws, 'SheetJS')
      XLSX.writeFile(wb, filename)
    },


  }
}
</script>

<style scoped>

</style>
